<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Http\Controller;

use Swoft;
use Swoft\Context\Context;
use Swoft\Exception\SwoftException;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Message\Request;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Annotation\Mapping\RequestMethod;
use Swoft\Http\Server\Annotation\Mapping\Middleware;
use Swoft\View\Renderer;

use App\Model\Entity\User as UserModel;
use App\Http\Middleware\AuthMiddleware;
use Throwable;

/**
 * Class HomeController
 * @Controller()
 */
class UserController
{
    /**
     * @RequestMapping()
     * @param Request $request
     * @param Response $response
     * @return Response
     * @throws Throwable
     */
    public function login(Request $request, Response $response): Response
    {
        $user_name = $request->input('user_name');
        $password  = $request->input('password');
        $user      = UserModel::where('user_name', $user_name)->first();
        if (!$user || true !== password_verify($password, $user->getPasswd())) {
            return json('账号或密码错误..', 401);
        }
        $user = $user->toArray();
        unset($user['password']);
        $user['token'] = makeToken($user);

        return json($user);
    }

    /**
     * @RequestMapping()
     * @Middleware(AuthMiddleware::class)
     * @param Request $request
     * @param Response $response
     * @return Response
     */
    public function info(Request $request, Response $response): Response
    {
        return json($request->user);
    }
}
